<script>
import ButtonList from '@/components/ButtonList'
import TableButtonList from '@/components/TableButtonList'
import WrapTable from '@/components/WrapTable'
import store from './store'
import Form from '@/components/Form'
import SearchForm from '@/components/SearchForm'
import { commonMixin } from '@/mixins/common'
import Tree from '@/components/WrapTree'
import ContainerList from '@/components/ContainerList'

export default {
  name: 'treeTableContainerList',
  inject: ['Dialog'],
  mixins: [store, commonMixin],
  components: {
    SearchForm,
    WrapTable,
    Form,
    ButtonList,
    TableButtonList,
    Tree,
    ContainerList
  },
  data() {
    return {
      // main
      idKey: 'deptId',
      pidKey: 'groupId',
      dialogType: '',
      isShowTitle: true, // 是否显示title

      // tree
      tree: {
        width: '280',
        height: '200',
        accordion: false,
        isShowHeader: false,
        treeMenuButtonList: [],
        treeOperateButtonList: [],
        showCheckbox: false,
        selectTree: {
          disabled: true,
          treeParams: {
            get: {
              url: '/v1/dataProvider/getGroupTreeList',
              idKey: 'id',
              nextNodeKey: 'pid'
            }
          },
          valueToLabelParams: {
            url: '/v1/dataProvider/getGroupName',
            idKey: 'groupId'
          },
          clearable: true,
          selectCodeVal: this.$store.getters.groupId || '',
          selectCodeKey: 'groupId',
          visibleChangeLoad: true
        },
        emptyTopNode: {
          expanded: true,
          id: '',
          leaf: false,
          text: '部门树'
        },
        nextNodeKey: 'node',
        idKey: 'deptId',
        search: {
          searchKey: 'deptName'
        },
        title: '',
        getNextChildNode: this.getNextNode,
        delNode: this.delNode
      },
      nodeCheckedKey: 'checked',
      nodeChildrenKey: 'children',
      nodeLeafKey: 'leaf',
      nodeIdKey: 'id',
      nodeLabelKey: 'text',
      currentNode: null,

      // table
      tableUniqueId: 'userId', // 表格唯一标识字符

      groupId: '',
      tableDefaultSort: { prop: 'funId', order: 'descending' },
      selectedList: [],
      tableSelectionCol: true,
      tableIndexCol: true,
      autoLoad: false,
      pagination: true,
      limitNum: 5,
      showInputFlag: true,
      searchInput: '',
      inputPlaceholder: '',
      btnListWidthPercent: 18,
      btnListWidthOffset: 0,
      searchInputWidthPercent: 6,
      searchInputWidthOffset: 0,
      tableOptWidth: '100',
      columns: [
        {
          prop: 'userNo',
          label: '账号',
          sortable: true,
          'show-overflow-tooltip': true,
          'header-align': 'left'
        },
        {
          prop: 'userName',
          label: '姓名',
          sortable: true,
          'show-overflow-tooltip': false,
          'header-align': 'left'
        },
        {
          prop: 'deptName',
          label: '部门',
          sortable: true,
          'show-overflow-tooltip': true,
          'header-align': 'left'
        }
      ],
      searchFields: [],
      searchModel: {},
      searchBtnList: [],
      toolPanelBtnList: [],
      tableRowBtnList: [],

      // containerList
      containerList: [],
      containerListTitle: '',
      titleKey: '',
      titleValue: ''
    }
  },
  computed: {
    data: {
      set(newVal) {
        this.store._data = newVal
      },
      get() {
        return this.store.data
      }
    },
    total() {
      return this.store.total
    },
    containerListLength() {
      return this.containerList.length
    },
    dataLength() {
      return this.data.length
    }
  },

  methods: {
    handleTreeSubSelect(val) {
      val && (this[this.pidKey] = val)
      !val && (this[this.pidKey] = '')
    },
    handleDeleteTag(data) {
      const value = data[this.tableUniqueId]
      for (let i = 0; i < this.dataLength; ++i) {
        if (value === this.store.data[i][this.tableUniqueId]) {
          this.$refs.table.toggleRowSelection(this.store.data[i], false)
          break
        }
      }
      for (let i = 0; i < this.containerListLength; ++i) {
        if (value === this.containerList[i][this.tableUniqueId]) {
          this.containerList.splice(i, 1)
          break
        }
      }
    },
    handleSelect(selection, row) {
      let flag = false
      for (let i = 0; i < selection.length; ++i) {
        if (row[this.tableUniqueId] === selection[i][this.tableUniqueId]) {
          flag = true
          break
        }
      }
      if (!flag) {
        for (let i = 0; i < this.containerListLength; ++i) {
          if (
            row[this.tableUniqueId] ===
            this.containerList[i][this.tableUniqueId]
          ) {
            this.containerList.splice(i, 1)
            break
          }
        }
      }
    },
    handleSelectAll(selection) {
      if (selection.length === 0) {
        for (let i = 0; i < this.dataLength; ++i) {
          for (let j = 0; j < this.containerListLength; ++j) {
            if (
              this.store.data[i][this.tableUniqueId] ===
              this.containerList[j][this.tableUniqueId]
            ) {
              this.containerList.splice(j, 1)
              break
            }
          }
        }
      }
    },
    handleSelectionChange(val) {
      this.selectedList = val
      for (let i = 0; i < this.selectedList.length; ++i) {
        let flag = false
        for (let j = 0; j < this.containerListLength; ++j) {
          if (
            this.containerList[j][this.tableUniqueId] ===
            this.selectedList[i][this.tableUniqueId]
          ) {
            flag = true
            break
          }
        }
        !flag ? this.containerList.push(this.selectedList[i]) : ''
      }
    },
    handleReturnSelectedList() {
      return this.containerList
    },
    handleEmptySelectedList() {
      this.containerList = []
      this.selectedList = []
      this.$refs.searchInput.clear()
      this.$refs.table.clearSelection()
    },
    handleNodeCheck(node) {
      if (node) {
        this.currentNode = node
        this.store._searchParams = {}
        this.store._searchParams['q_' + this.idKey] = node.data[this.nodeIdKey]
        this.$refs.table.load(1, this.store.limit)
        this.selectedList = this.containerList
      }
    },
    handleCheckCheckbox() {
      this.$nextTick(() => {
        for (let i = 0; i < this.containerListLength; ++i) {
          for (let j = 0; j < this.dataLength; ++j) {
            if (
              this.containerList[i][this.tableUniqueId] ===
              this.store.data[j][this.tableUniqueId]
            ) {
              this.$refs.table.toggleRowSelection(this.store.data[j], true)
              break
            }
          }
        }
      })
    },
    handleInputClick(_ev, _val) {},
    handleTreeEmpty() {
      this.data = []
    },
    getData({ page, limit }) {
      this.store &&
        (this.store._searchParams[`q_${this.pidKey}`] = this[this.pidKey])
      this.store.read({ start: page, limit: limit })
    },
    // 自定义containerListTag内容
    // eslint-disable-next-line
    formaterTagContent(item) {
      return ''
    },
    renderTitle() {
      return (
        <div class='ttc-title'>
          {this.titleKey}: {this.titleValue}
        </div>
      )
    },
    renderTree() {
      return (
        <Tree
          ref='tree'
          tree={this.tree}
          on-check-treeNode={this.handleNodeCheck}
          on-tree-empty={this.handleTreeEmpty}
          on-tree-subSelect={this.handleTreeSubSelect}></Tree>
      )
    },
    renderWrapTable() {
      const propsObj = {
        ref: 'table',
        props: {
          getData: this.getData,
          total: this.total,
          data: this.data,
          fields: this.columns,
          selectionCol: this.tableSelectionCol,
          indexCol: this.tableIndexCol,
          autoLoad: this.autoLoad,
          pagination: this.pagination,
          limitNum: this.limitNum,
          paginationLayout: '->, prev, pager, next',
          'tooltip-effect': 'dark',
          border: true,
          stripe: true,
          'default-sort': this.tableDefaultSort
        },
        on: {
          'selection-change': this.handleSelectionChange,
          select: this.handleSelect,
          'select-all': this.handleSelectAll
        }
      }

      return (
        <WrapTable {...propsObj}>
          {this.searchBtnList && this.searchBtnList.length > 0 ? (
            <SearchForm
              items={this.searchFields}
              props-model={this.searchModel}
              slot='searchPanel'
              ref='searchForm'>
              <ButtonList
                operateBtnList={this.searchBtnList}
                props-model={this.searchModel}></ButtonList>
            </SearchForm>
          ) : (
            ''
          )}

          <c-row slot='toolPanel' class='toolPanel'>
            <c-col
              span={this.btnListWidthPercent}
              offset={this.btnListWidthOffset}>
              <ButtonList operateBtnList={this.toolPanelBtnList}></ButtonList>
            </c-col>
            <c-col
              span={this.searchInputWidthPercent}
              justify='end'
              offset={this.searchInputWidthOffset}>
              {this.showInputFlag ? (
                <c-input
                  class='search-input'
                  ref='searchInput'
                  placeholder={this.inputPlaceholder}
                  size='small'
                  v-model={this.searchInput}
                  value={this.searchInput}
                  on-input={event => {
                    this.searchInput = event
                  }}
                  nativeOnKeydown={ev => {
                    ev.keyCode === 13
                      ? this.handleInputClick(ev, this.searchInput)
                      : null
                  }}>
                  <i
                    slot='suffix'
                    class='el-input__icon el-icon-search'
                    on-click={ev =>
                      this.handleInputClick(ev, this.searchInput)
                    }></i>
                </c-input>
              ) : (
                ''
              )}
            </c-col>
          </c-row>

          {this.haveTool ? (
            <c-table-column
              label='操作'
              align='center'
              slot='toolbar'
              fixed='right'
              width={this.tableOptWidth}
              {...{
                scopedSlots: {
                  default: scope => {
                    return (
                      <TableButtonList
                        operateBtnList={this.tableRowBtnList}
                        props-model={scope.row}
                      />
                    )
                  }
                }
              }}
            />
          ) : (
            ''
          )}
        </WrapTable>
      )
    },
    renderContainerList() {
      return (
        <ContainerList
          class='container-list'
          ref='containerList'
          title={this.containerListTitle}
          equal={(a, b) => {
            return a[this.tableUniqueId] === b[this.tableUniqueId]
          }}
          formater={this.formaterTagContent}
          value={this.containerList}
          on-deleteItem={this.handleDeleteTag}></ContainerList>
      )
    },
    renderCustom() {
      return this._e()
    }
  },
  render() {
    return (
      <div class='tree-table-container-list'>
        {this.isShowTitle ? this.renderTitle() : ''}
        <div class='tree-table'>
          <div class='tree-table-left tree-left'>{this.renderTree()}</div>
          <div class='tree-table-right'>{this.renderWrapTable()}</div>
        </div>
        {this.renderContainerList()}
        {this.renderCustom()}
      </div>
    )
  }
}
</script>

<style lang="scss">
.tree-table-container-list {
  height: 500px;
  box-sizing: border-box;
  .ttc-title {
    font-size: 14px;
    height: 22px;
    font-size: 16px;
    font-family: PingFangSC-Semibold, PingFang SC;
    font-weight: 600;
    color: rgba(0, 0, 0, 0.85);
    line-height: 22px;
    margin-bottom: 20px;
  }
  .tree-table {
    height: 350px;
    box-sizing: border-box;
    display: flex;
    .tree-table-left {
      padding-left: 0;
      height: 100%;
      width: 340px;
      .panel {
        width: 320px !important;
        .el-tree {
          width: 320px !important;
          overflow-x: auto;
          .el-tree-node {
            min-width: 300px !important;
          }
        }
      }
      .is-empty.el-scrollbar {
        max-height: 253px !important;
        height: 253px !important;
        .el-select-dropdown__list {
          padding-top: 0;
          .expand-tree {
            margin-top: 0;
          }
        }
      }
      .header {
        display: none;
      }
      .select-wrap {
        padding: 0 !important;
      }
      .search-input {
        margin: 10px 0 !important;
      }
    }
    .tree-table-right {
      box-sizing: border-box;
      border-left: 1px solid #dddfe7;
      padding-left: 20px;
      flex: 1;
      .wrap-table {
        height: 100%;
        .toolPanel {
          margin-top: 0 !important;
          margin-bottom: 10px !important;
          display: flex;
          justify-content: flex-end !important;
        }
        .search-input {
          width: 100% !important;
          height: 32px;
          input {
            height: 32px;
          }
          .el-input__suffix {
            cursor: pointer;
          }
          .el-input__icon {
            font-size: 14px;
            height: 32px !important;
            line-height: 32px !important;
          }
        }
        .cp-search-form {
          padding-bottom: 0;
          .el-form {
            width: inherit;
          }
        }
        .pagination {
          margin: 10px 0 !important;
        }
      }
    }
  }
  .container-list {
    height: 112px;
    margin-top: 20px;
  }
}
</style>
